package demo.sicua.votesystem.controller;

import demo.sicua.votesystem.entity.PO.UserPO;
import demo.sicua.votesystem.entity.VO.ResultVO;
import demo.sicua.votesystem.service.AdminService;
import demo.sicua.votesystem.service.UserService;
import demo.sicua.votesystem.util.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @RestController ： 将类装载到Javabean里面去
 * UserController -> UserService -> UserServiceImp ->UserDao -> UserMapping->db
 */
@RestController   //@Controller+@ResponseBody
@RequestMapping("/user")
public class Usercontroller {

    /**
     * 自动装载
     */
    @Autowired
    private UserService userService;

    @Autowired
    private AdminService adminService;

    @GetMapping("/getAllUser")
    public ResultVO getAllUser(){
        return userService.getAllUser();
    }

    /**
     * @param page
     * @param limit
     * @return
     */
    /* page 当前页数,limit 可显示最大数*/
    @GetMapping("/getUser")
    public ResultVO getUser(@RequestParam("page") int page,
                            @RequestParam("limit") int limit){
        return userService.getUser(page,limit);
    }

    @PostMapping("/login")
    public ResultVO login(@RequestParam("username")String username,
                          @RequestParam("password") String password,
                          @RequestParam("admin") String admin,
                          HttpServletRequest request){
        if (Integer.parseInt(admin) == 0){
            return userService.login(username,password,request);
        }else {
            return adminService.loginAdmin(username,password,request);
        }
    }

    @PostMapping("/deleteUserById")
    public ResultVO deleteUserById(@RequestParam("uid") String uid){
        return userService.deleteUserById(uid);
    }

    @PostMapping("/addUser")
    public ResultVO addUser(@RequestParam("username") String username,
                            @RequestParam("password") String password,
                            @RequestParam("realName") String realName,
                            @RequestParam(name = "email",required = false) String email,
                            @RequestParam("role") String role){
        UserPO userPO = new UserPO(IDUtil.getUUID(),username,password,realName,email,role);
        return userService.addUser(userPO);
    }

    @GetMapping("/updateUser")
    public ResultVO updateUser(@RequestParam("uid") String uid,
                               @RequestParam("password") String password,
                            @RequestParam("realName") String realName,
                            @RequestParam(name = "email",required = false) String email,
                            @RequestParam("role") String role){
        UserPO userPO = new UserPO(uid,password,realName,email,role);
        return userService.updateUser(userPO);
    }
}
